#!/bin/bash

set -e

source $SRCROOT/integration/common

title 'Service Agreement test.'

fixtures_path=$SRCROOT/integration-scripts/src/fixtures
template_path=$fixtures_path/agreement_template.json
current_spec_path=$fixtures_path/agreement.json
# Read in the spec template, and point it to the mean aggregator contract.
jq ".aggregator=\"$MEAN_AGGREGATOR_ADDRESS\" | .oracles=[\"$CHAINLINK_NODE_ADDRESS\"]" < $template_path > $current_spec_path

create_sa="chainlink -j agreements create $current_spec_path"
agreement_response=$($create_sa)

function query_agreement() {
    echo "$agreement_response" | jq -r .$1
}

function check_sa_output() {
    cl_output=$(query_agreement $1)
    cl_input=$(jq -r .$2 < $current_spec_path)
    if [ -z "$cl_output" ] ; then echo "output for $1 was empty"; exit 1; fi
    if [ -z "$cl_input" ] ; then echo "input for $2 was empty"; exit 1; fi
    if [ "$cl_output" != "$cl_input" ]; then
        echo "mismatch for $1/$2: $cl_output $cl_input"; exit 1;
    fi
}

check_sa_output encumbrance.payment                payment
check_sa_output encumbrance.expiration             expiration
check_sa_output encumbrance.oracles                oracles
check_sa_output encumbrance.aggregator             aggregator
check_sa_output encumbrance.aggInitiateJobSelector aggInitiateJobSelector
check_sa_output encumbrance.aggFulfillSelector     aggFulfillSelector

# Used in initiate_service_agreement.js
export ORACLE_SIGNATURE=$(query_agreement signature)
export NORMALIZED_REQUEST=$(query_agreement requestBody)
export SERVICE_AGREEMENT=$(cat $current_spec_path)
rm $current_spec_path # Remove temp file

echo "ORACLE_SIGNATURE" $ORACLE_SIGNATURE
echo "NORMALIZED_REQUEST" $NORMALIZED_REQUEST
echo "SERVICE_AGREEMENT" $SERVICE_AGREEMENT

yarn workspace @chainlink/integration-scripts initiate-service-agreement
